'use strict';
const {
  Model
} = require('sequelize');
module.exports = (sequelize, DataTypes) => {
  class Article extends Model {
    /**
     * Helper method for defining associations.
     * This method is not a part of Sequelize lifecycle.
     * The `models/index` file will call this method automatically.
     */
    static associate(models) {
      // define association here
      models.Article.belongsToMany(models.Category, { through: models.CategoryArticle, foreignKey: 'articleId', as: 'categories' });
    }
  }
  Article.init({
    contentZh: DataTypes.JSON,
    contentEn: DataTypes.JSON,
    slug: {
      type: DataTypes.STRING,
      allowNull: false,
      validate: {
        notNull: {msg: 'slug必填'},
        notEmpty: {msg: 'slug不能为空'},
        len: {
          args: [2, 45],
          msg: 'slug长度在2-45个字符之间'
        },
        async isUnique(value) {
          const article = await Article.findOne({ where: { slug: value } })
          if (article) {
            throw new Error('slug已经存在。');
          }
        }
      }
    },
    titleZh: {
      type: DataTypes.STRING,
      allowNull: false,
      validate: {
        notNull: {msg: '中文标题必填'},
        notEmpty: {msg: '中文标题不能为空'},
        len: {
          args: [2, 45],
          msg: '中文标题长度在2-45个字符之间'
        },
      }
    },
    titleEn: {
      type: DataTypes.STRING,
      allowNull: false,
      validate: {
        notNull: {msg: '英文标题必填'},
        notEmpty: {msg: '英文标题不能为空'},
        len: {
          args: [2, 45],
          msg: '英文标题长度在2-45个字符之间'
        },
      }
    },
    authorId: {
      type: DataTypes.INTEGER,
      allowNull: false,
      validate: {
        notNull: {msg: '作者ID不能为空'},
        isInt: {msg: '作者ID必须为整数'}
      }
    },
    status: {
      allowNull: false,
      defaultValue: 2,
      type: DataTypes.ENUM('1', '2', '3', '4'),
      validate: {
        isIn: {
          args: [['1', '2', '3', '4']],
          msg: '状态值必须是 1(草稿)、2(审核中)、3(上架)、4(下架)之一'
        }
      }
    },
    coverImg: DataTypes.STRING
  }, {
    sequelize,
    modelName: 'Article',
  });
  return Article;
};